<script setup>
import { ref, reactive, watch } from "vue";

const props = defineProps({
  modelValue: {
    type: String || Number,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  echo: {
    type: String,
    default: ''
  },
  columns: {
    type: Array,
    default: () => ([])
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  isRemote: {
    type: Boolean,
    default: false
  },
  remoteParams: {
    type: Object,
    default: () => ({})
  }
})

const pageData = reactive({
  popupData: []
})
const emit = defineEmits(['update:modelValue'])
const showPopup = ref(false)
const handlePopup = () => {
  if (props.disabled) return
  showPopup.value = true
  if (props.isRemote) {
    props.remoteParams.api(props.remoteParams.params).then(res => {
      pageData.popupData = res[props.remoteParams.resField || 'data'].map(item => {
        return {
          text: item[props.remoteParams.field.text],
          value: item[props.remoteParams.field.value]
        }
      })
    })
  }
}
watch(
    () => props.modelValue,
    (nv, ov) => {
      const values = props.isRemote ? pageData.popupData.map(item => item.value) : props.columns.map(item => item.value)
      const index = values.indexOf(nv)
      iptValue.value = props.echo ? props.echo : props.isRemote ? pageData.popupData[index]?.text : props.columns[index]?.text
      console.log('nv-modelValue', nv, values, index, iptValue.value)
    }
)
const popupConfirm = (v) => {
  console.log('v', v, v.selectedValue[0])
  showPopup.value = false
  const values = props.isRemote ? pageData.popupData.map(item => item.value) : props.columns.map(item => item.value)
  const index = values.indexOf(v.selectedValue[0])
  if (props.isRemote) {
    iptValue.value = pageData.popupData[index].text
  } else {
    iptValue.value = props.columns[index].text
  }
  emit('update:modelValue', v.selectedValue[0])
}
const iptValue = ref('')
</script>

<template>
  <nut-input v-model="iptValue" readonly :placeholder="placeholder" type="text" @click="handlePopup" />
  <nut-popup position="bottom" v-model:visible="showPopup">
    <nut-picker
        :value="modelValue"
        :columns="isRemote ? pageData.popupData : columns"
        :title="title"
        @confirm="popupConfirm"
    >
    </nut-picker>
  </nut-popup>
</template>

<style scoped lang="scss">

</style>
